package com.mdxq.mall.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mdxq.mall.user.entity.RoleMenuRelation;
import com.mdxq.mall.user.entity.RoleResourceRelation;
import com.mdxq.mall.user.mapper.RoleMenuRelationMapper;
import com.mdxq.mall.user.mapper.RoleResourceRelationMapper;
import com.mdxq.mall.user.service.RoleMenuRelationService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.mdxq.mall.user.entity.Role;
import com.mdxq.mall.user.mapper.RoleMapper;
import com.mdxq.mall.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 后台用户角色表 服务层实现。
 *
 * @author ShuJie
 * @since 2025-01-12
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>  implements RoleService{
    @Autowired
    private RoleMenuRelationMapper relationMapper;

    @Transactional
    @Override
    public boolean allocMenu(Long roleId, String menuIds) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("role_id",roleId);
        relationMapper.deleteByQuery(queryWrapper);
        if(StrUtil.isNotBlank(menuIds)){
            List<RoleMenuRelation>relations=new ArrayList<>();
            for (String menuId:menuIds.split(",")){
                relations.add(new RoleMenuRelation(null,roleId,Long.valueOf(menuId)));
            }
            relationMapper.insertBatch(relations);
        }
        return true;
    }
    @Autowired
    private RoleResourceRelationMapper resourceRelationMapper;

    @Override
    @Transactional
    public boolean allocResource(Long roleId, String resourceIds) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("role_id",roleId);
        resourceRelationMapper.deleteByQuery(queryWrapper);
        if(StrUtil.isNotBlank(resourceIds)){
            List<RoleResourceRelation> relations=new ArrayList<>();
            for(String resourceId:resourceIds.split(",")){
                relations.add(new RoleResourceRelation(null,roleId,Long.valueOf(resourceId)));
            }
            resourceRelationMapper.insertBatch(relations);
        }
        return true;
    }
}
